﻿using CoreLims.Models.CoreLims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System.Linq;

namespace CoreLims.Controllers
{
    [Authorize]
    public class WikiController : Controller
    {
        private readonly CoreLimsContext dbContext;
        public WikiController(CoreLimsContext context)
        {
            dbContext = context;
        }

        public ViewResult WikiManager() => View();

        public ViewResult WikiFileManager() => View();

        [HttpPost]
        public JsonResult GetWikiRoots() // 获取文档库根目录
        {
            var first = Wiki.Library.getLibrarys(dbContext)
                .OrderBy(s => s.Name)
                .Select(s => new { s.Id, s.Name })
                .ToArray();

            return Json(first);
        }

        [HttpPost]
        public string CreateWikiLibrary(string LibraryName) // 创建文档库
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            return Wiki.Library.CreateLibrary(dbContext, LibraryName, user.Id, user.FullName);
        }

        [HttpPost]
        public string SearchDirectory(string WikiId) // 查询当前选择的目录位置
        {
            return Wiki.Library.SearchDirectory(dbContext, WikiId);
        }

        [HttpPost]
        public string AddDirectory(string ParentDirectory, string DirectoryName) // 添加目录
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            return Wiki.Library.AddDirectory(dbContext, ParentDirectory, DirectoryName, user.Id, user.FullName);
        }

        [HttpPost]
        public JsonResult GetDirectoryAndPage(string WikiId) // 获取指定目录下的目录和文章列表
        {
            var Directory = Wiki.Library.SearchDirectory(dbContext, WikiId);
            if (string.IsNullOrEmpty(Directory))
            {
                return Json(null);
            }
            else
            {
                var relist = Wiki.Library.getDirectorys(dbContext, Directory)
                    .Select(s => new { s.Id, s.Name, IsDirectory = true }).OrderBy(x => x.Name).ToList();

                var list = Wiki.Page.getPages(dbContext, Directory)
                    .Select(s => new { s.Id, Name = s.Title, IsDirectory = false }).OrderBy(x => x.Name).ToList();

                var level = 0;
                foreach (var item in Directory)
                {
                    if (item == '\\')
                        level++;
                }

                var result = new Common.PageHelper();
                relist.AddRange(list);
                result.rows = relist.ToArray();
                result.total = level;

                return Json(result);
            }
        }

        [HttpPost]
        public string CreateWikiPage(string Title, string ParentDirectory) // 创建文档库文章
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            return Wiki.Page.CreatePage(dbContext, Title, user.Id, user.FullName, ParentDirectory);
        }

        [HttpPost]
        public JsonResult GetWikiPage(string PageId) // 获取文档库文章
        {
            var page = Wiki.Page.getPage(dbContext, PageId);
            return Json(page);
        }
        
        [HttpPost]
        public string SaveWikiPage(string PageId, string Content) // 保存文章内容
        {
            if (string.IsNullOrEmpty(Content))
                return "保存内容不能为空！";

            var page = Wiki.Page.getPage(dbContext, PageId);
            page.TextContent = Content;

            dbContext.Page.Update(page);
            dbContext.SaveChanges();
            return "保存成功！";
        }

        [HttpPost]
        public JsonResult GetWikiPageComment(string PageId, string limit, string offset) // 获取文章相关的评论
        {
            var comments = Wiki.PageComment.getPageComment(dbContext, PageId)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var res = new Common.PageHelper();
            res.total = Wiki.PageComment.getPageComment(dbContext, PageId).Count;
            res.rows = comments;

            return Json(res);
        }

        [HttpPost]
        public string SaveWikiPageComment(string PageId, string Comment) // 保存文章评论
        {
            if (string.IsNullOrEmpty(Comment))
                return "保存内容不能为空！";

            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            var comment = new WikiPageComment();
            comment.PageId = PageId;
            comment.Comment = Comment;
            comment.CreatorId = user.Id;
            comment.CreatorName = user.FullName;

            dbContext.PageComment.Add(comment);
            dbContext.SaveChanges();
            return "文章评论保存成功！";
        }

        #region 文件管理

        [HttpPost]
        public JsonResult getTopLevel(string ParentDirectory)
        {
            var list = Wiki.FileManager.getTopLevel(dbContext);
            return Json(list);
        }

        [HttpPost]
        public JsonResult getFileDirectory(string ParentDirectory, string DirectoryId)
        {
            var list = Wiki.FileManager.getDirectory(dbContext, DirectoryId);
            var level = 0; // 目录级别，用来控制前端显示时的缩进
            if (list.Count > 0)
            {
                var fir = list[0];
                while(fir != null)
                {
                    fir = Wiki.FileManager.getFileManager(dbContext, fir.ParentDirectory);
                    level++;
                    if (fir == null || fir.ParentDirectory == null) { break; }
                }
            }

            var result = new Common.PageHelper();
            result.rows = list.ToArray();
            result.total = level;

            return Json(result);
        }

        [HttpPost]
        public JsonResult getWikiFiles(string limit, string offset, string DirectoryId)
        {
            var list = Wiki.FileManager.getWikiFiles(dbContext, DirectoryId)
                .Skip(int.Parse(offset)).Take(int.Parse(limit))
                .ToArray();

            var result = new Common.PageHelper();
            result.rows = list.ToArray();
            result.total = Wiki.FileManager.getWikiFiles(dbContext, DirectoryId).Count;

            return Json(result);
        }

        [HttpPost]
        public string SearchFileDirectory(string FileId)
        {
            return Wiki.FileManager.SearchFileDirectory(dbContext, FileId);
        }

        [HttpPost]
        public string AddFileDirectory(string ParentDirectory, string DirectoryName) // 添加目录
        {
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);
            return Wiki.FileManager.CreateDirectory(dbContext, DirectoryName, user.Id, user.FullName, ParentDirectory);
        }

        [HttpPost]
        public string CreateWikiFile(string jsonStr)
        {
            var file = JsonConvert.DeserializeObject<WikiFileManager>(jsonStr);  //反序列化，字符串转换为类
            var user = Common.User.getUserByIdentityName(dbContext, HttpContext.User.Identity.Name);

            file.CreatorId = user.Id;
            file.CreatorName = user.FullName;

            dbContext.Add(file);
            dbContext.SaveChanges();
            return "文件添加成功！";
        }

        [HttpPost]
        public string UpdateWikiFileVersion(string Id, string Version)
        {
            var file = Wiki.FileManager.getFileManager(dbContext, Id);
            int a = 1;
            if (int.TryParse(Version, out a))
            { 
                file.Version = a;
                dbContext.Update(file);
                dbContext.SaveChanges();
                return "版本号更新成功！";
            } 
            else { return "版本号必需是整数！"; }

        }

        [HttpPost]
        public string UpdateWikiFileRevise(string Id, string Revise)
        {
            var file = Wiki.FileManager.getFileManager(dbContext, Id);
            file.Revise = Revise;
            dbContext.Update(file);
            dbContext.SaveChanges();
            return "修订更新成功！";
        }

        [HttpPost]
        public string UpdateWikiFileEffectiveDate(string Id, string EffectiveDate)
        {
            var file = Wiki.FileManager.getFileManager(dbContext, Id);
            file.EffectiveDate = EffectiveDate;
            dbContext.Update(file);
            dbContext.SaveChanges();
            return "生效日期更新成功！";
        }

        [HttpPost]
        public string DeleteWikiFile(string Id)
        {
            var file = Wiki.FileManager.getFileManager(dbContext, Id);
            var ufile = Common.UploadFile.getIdsByDomain(dbContext, "WikiFile", Id);

            var path = Common.getGlobalKeyValue(dbContext, "WikiFileText_Path");
            var fileName = path + "\\" + Id + ".txt";
            if (System.IO.File.Exists(fileName))
            {
                System.IO.File.Delete(fileName);
            }

            dbContext.WikiFileManager.Remove(file);
            foreach (var u in ufile)
                dbContext.UploadFile.Remove(u);
            dbContext.SaveChanges();
            return "文件删除成功！";
        }

        #endregion
    }
}
